package com.ruan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruan.mapper.*;
import com.ruan.pojo.*;
import com.ruan.pojoExt.EmployeeExt;
import com.ruan.pojoExt.ProjectExt;
import com.ruan.pojoExt.TaskExt;
import com.ruan.service.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.sql.Date;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.ruan.pojo.Project.CompletionStatus.onGoing;

@Service//交由spring容器进行管理//  mybatis-plus提供的规范，继承父类，实现父接口
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private EmployeeMapper employeeMapper;

    @Autowired
    private ProjectAssignmentsMapper projectAssignmentsMapper;

    @Autowired
    private ProjectToolAssignmentMapper projectToolAssignmentMapper;

    @Autowired
    private ParticipantMapper participantMapper;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private ParticipantService participantService;

    @Autowired
    private TasksMapper tasksMapper;

    @Autowired
    private ClientService clientService;

    @Autowired
    private FileMapper fileEntityMapper;

    @Autowired
    private FileCloudMapper fileCloudMapper;

    @Override
    public List<ProjectExt> getTodayProjects(String employeeId) {
        LocalDate currentDate = LocalDate.now();
        LambdaQueryWrapper<Project> queryWrapper = new LambdaQueryWrapper<>();
//        System.out.println("employeeId是"+employeeId);
        queryWrapper.eq(Project::getEmployeeId, employeeId);

        // 从数据库中获取该员工(项目经理)今天未完成的项目
        queryWrapper.eq(Project::getEmployeeId, employeeId)
                .ge(Project::getEndDate, currentDate) // 获取截止时间大于等于当前日期的任务
                .ne(Project::getCompletionStatus, "completed");// 获取completeStatus不为completed的项目
        List<Project> projectList = projectMapper.selectList(queryWrapper);
        List<ProjectExt> projectExtList = new ArrayList();
        for(Project project : projectList){
            ProjectExt projectExt = new ProjectExt();
            BeanUtils.copyProperties(project,projectExt);

            Client client = clientService.getById(project.getClientId());
            projectExt.setClientName(client.getName());

            LambdaQueryWrapper<Participant> queryWrapper1 = new LambdaQueryWrapper<>();
            queryWrapper1.eq(Participant::getProjectId,project.getId());
            List<Participant> participantList = participantMapper.selectList(queryWrapper1);

            List<Long> employeeIds = new ArrayList<>();
            for(Participant participant : participantList) {
                LambdaQueryWrapper<Tasks> queryWrapper2 = new LambdaQueryWrapper();
                queryWrapper2.eq(Tasks::getEmployeeId, participant.getEmployeeId())//已经有任务的组员就不提醒了
                        .ge(Tasks::getDeadline, currentDate); // 获取截止时间大于等于当前日期的任务
                List<Tasks> tasksList = tasksMapper.selectList(queryWrapper2);

                for (Tasks tasks : tasksList) {
                    employeeIds.add(tasks.getEmployeeId());
                }

            }
            System.out.println("employeeIds有当前时间没有任务的参与人员的id吗"+employeeIds);
            //获取当前时间没有任务的参与人员
            queryWrapper1.notIn(!employeeIds.isEmpty(),Participant::getEmployeeId,employeeIds);

            List<Participant> participantListWithOutTask = participantMapper.selectList(queryWrapper1);
            List<Employee> employeeList = new ArrayList<>();
            for(Participant participant : participantListWithOutTask){
//                Employee employee = employeeService.getById(participant.getEmployeeId());
               LambdaQueryWrapper<Employee> queryWrapper2 = new LambdaQueryWrapper();
                queryWrapper2.eq(Employee::getId,participant.getEmployeeId())
                                .notIn(Employee::getStatus,"离职","待审核");//离职和待审核的也不能安排任务
                Employee employee = employeeMapper.selectOne(queryWrapper2);
                System.out.println("employee的状态是"+employee);
                if(employee!=null){//防止把空的也存入
                    employeeList.add(employee);
                }

            }
            projectExt.setEmployeeList(employeeList);
            projectExtList.add(projectExt);
        }
        System.out.println("projectExtList有什么"+projectExtList);
        return projectExtList;
    }

    /**
     * 将项目信息导出为Excel
     * @throws Exception
     * @return
     */
    @Override
    public byte[] exportToExcel() {
        List<Project> projectList = projectMapper.selectList(null);
//        为在调用PoiUtils类的exportClientInfo方法时，该方法是非静态方法，
//        而你是通过类名直接调用的，需要先创建PoiUtils对象再调用该方法。
//        PoiUtils poiUtils = new PoiUtils();
//        poiUtils.exportClientInfo(clientList);

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        XSSFWorkbook excel=new XSSFWorkbook(); //工作簿，允许您在Java应用程序中创建、读取和修改Excel文件
        //创建一个工作表对象
        XSSFSheet sheet = excel.createSheet("sheet1");


        String[] headers = {"客户姓名","项目名", "负责人",
                "部门名", "项目内容", "截止时间",
                "创建时间","更新时间","完成时间"
                ,"完成状态","支付状态","支付时间"
                ,"支付方式","预计收入","实际收入(实付款)"
                ,"预计成本","实际成本","所得税率","净利润"};

        XSSFRow row1 = sheet.createRow(0); // Create the first row for headers

        for (int i = 0; i < headers.length; i++) {
            row1.createCell(i).setCellValue(headers[i]); // Create cell for each header
        }

        for (int i = 0; i < projectList.size(); i++) {
            Project project = projectList.get(i);
            LocalDateTime endDate = project.getEndDate();
            LocalDateTime createTime = project.getCreateTime();
            LocalDateTime updateTime = project.getUpdateTime();
//            if(project.getCompletionTime() != null){
                LocalDateTime completionTime = project.getCompletionTime();
//            }

//            if(project.getCheckoutTime() != null) {
                LocalDateTime checkoutTime = project.getCheckoutTime();
//            }
            XSSFRow row2 = sheet.createRow(i+1);

            Project.CompletionStatus completeStatus = project.getCompletionStatus();
            String completeStatusText = (completeStatus == onGoing) ? "进行中" : "已完成";

            int payStatus = project.getPayStatus();
            String payStatusText = (payStatus == 0) ? "待付款" : (payStatus == 1) ? "已付款" : "已取消";

            int payMethod = project.getPayMethod();
            String payMethodText = (payMethod == 0) ? "银行卡" : (payMethod == 1) ? "微信" : "支付宝";

            Client client = new Client();
            Employee employee = new Employee();
            Department department = new Department();

            if(project != null){
                if(project.getClientId() != null) {
                    client = clientService.getById(project.getClientId());//报空指针。。。。。。啊啊啊啊
                }
                if(project.getEmployeeId() != null) {
                    employee = employeeService.getById(project.getEmployeeId());//报空指针。。。。。。啊啊啊啊
                }
                if(project.getDepartmentId() != null) {
                    department = departmentService.getById(project.getDepartmentId());//报空指针。。。。。。啊啊啊啊
                }

                String[] clientInfo = {
                        client.getName(),project.getProjectName(), employee.getName(),
                        department.getName(),project.getDescription(), String.valueOf(endDate),
                        String.valueOf(createTime), String.valueOf(updateTime),
                        completionTime != null ? String.valueOf(completionTime) : "",
                        completeStatusText,payStatusText,
                        checkoutTime != null ? String.valueOf(checkoutTime) : "",
                        payMethodText, String.valueOf(project.getAmount()),
                        project.getActualAmount() != null ? String.valueOf(project.getActualAmount()) : "",
                        String.valueOf(project.getCost()),
                        project.getActualCost() != null ? String.valueOf(project.getActualCost()) : "",
                        String.valueOf(project.getTax()),
                        project.getProfit() != null ? String.valueOf(project.getProfit()) : ""
                };

                for (int j = 0; j < clientInfo.length; j++) {
                    row2.createCell(j).setCellValue(clientInfo[j]);
                }
            }
        }

        HttpHeaders header = new HttpHeaders();
        header.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
        header.setContentDispositionFormData("attachment", "项目表.xlsx");
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        try {
            excel.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            excel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return outputStream.toByteArray();

    }


    /**
     * 删除项目操作
     * @param id 项目id
     * @return
     */
    @Override
    public Boolean deleteProject(Integer id) {
        LambdaQueryWrapper<Project> projectQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<ProjectAssignments> projectAssignmentsQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<ProjectToolAssignment> projectToolAssignmentQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<Participant> participantQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<Tasks> tasksQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<FileEntity> fileEntityQueryWrapper = new LambdaQueryWrapper();
        LambdaQueryWrapper<FileCloudEntity> fileCloudEntityQueryWrapper = new LambdaQueryWrapper();

//        projectQueryWrapper.eq(Project::getId,id);
//        Project project = projectMapper.selectOne(projectQueryWrapper);

        Project project = projectMapper.selectById(id);
        if (project!=null){
            projectAssignmentsQueryWrapper.eq(ProjectAssignments::getProjectId,project.getId());
            projectToolAssignmentQueryWrapper.eq(ProjectToolAssignment::getProjectId,project.getId());
            participantQueryWrapper.eq(Participant::getProjectId,project.getId());
            tasksQueryWrapper.eq(Tasks::getProjectId,project.getId());
            fileEntityQueryWrapper.eq(FileEntity::getProjectId,project.getId());
            fileCloudEntityQueryWrapper.eq(FileCloudEntity::getProjectId,project.getId());

            List<ProjectAssignments> projectAssignmentsList = projectAssignmentsMapper.selectList(projectAssignmentsQueryWrapper);
            if (projectAssignmentsList.size()>0){
                projectAssignmentsMapper.delete(projectAssignmentsQueryWrapper);//删除对应的分配表记录
            }

            List<ProjectToolAssignment> projectToolAssignmentList = projectToolAssignmentMapper.selectList(projectToolAssignmentQueryWrapper);
            if (projectToolAssignmentList.size()>0){
                projectToolAssignmentMapper.delete(projectToolAssignmentQueryWrapper);//删除对应的分配表记录
            }

            List<Participant> participantList = participantMapper.selectList(participantQueryWrapper);
            if (participantList.size()>0){
                participantMapper.delete(participantQueryWrapper);//删除对应的项目参与人员
            }

            List<Tasks> tasksList = tasksMapper.selectList(tasksQueryWrapper);
            if (tasksList.size()>0){
                tasksMapper.delete(tasksQueryWrapper);//删除对应的项目的任务
            }

            List<FileEntity> fileEntityList = fileEntityMapper.selectList(fileEntityQueryWrapper);
            if (fileEntityList.size()>0){
                fileEntityMapper.delete(fileEntityQueryWrapper);//删除该项目的文件往来记录
            }

            List<FileCloudEntity> fileCloudEntityList = fileCloudMapper.selectList(fileCloudEntityQueryWrapper);
            if (fileCloudEntityList.size()>0){
                fileCloudMapper.delete(fileCloudEntityQueryWrapper);//删除该项目的云文件往来记录
            }
            //最后删除项目
            projectMapper.deleteById(project.getId());
            return true;
        }

        return false;
    }
}
